<?php
// +----------------------------------------------------------------------
// | 后台文章管理控制器
// +----------------------------------------------------------------------
// | Author: Eric <ieyangxiaoguo@126.com>
// +----------------------------------------------------------------------
// | Copyright ©2017 http://www.zzuyxg.top All rights reserved.
// +----------------------------------------------------------------------
// | 2017年10月12日
// +----------------------------------------------------------------------
namespace app\tdadmin\controller;

use app\common\controller\AdminBaseController;
use app\common\model\MemberModel;
use app\common\model\RequirementModel;
use app\common\model\RequirementTypeModel;
use app\common\model\TeacherModel;
use think\Db;

class RequirementController extends AdminBaseController
{
    /**
     * 文章列表
     */
    public function index()
    {
        $typeModel = new RequirementTypeModel();

        $categories = $typeModel->getAll();

        $this->assign('categories', $categories);

        return $this->fetch();
    }

    public function getRequirementList(){
        $map = [];
        $catID = $this->request->param('catID/d', 0, 'intval');
        $keyword = $this->request->param('keyword', '');

        // $map[] = ['post_type','=',0];

        if ($catID) {
            $map[] = ['type','=',$catID];
        }
        if ($keyword != '') {
            $map[] = ['title','like',$keyword.'%'];
        }

        $count = RequirementModel::where($map)->count();

        $page = $this->request->param('page',1,'intval');
        $limit = $this->request->param('limit',10,'intval');

        $lists = RequirementModel::where($map)->with(['requirement_type', "teacher", "member"])->order('id desc')->limit(($page-1)*$limit,$limit)->all();

        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $lists;
        $res['count'] = $count;
        return $res;
    }


    public function addTag()
    {
        if ($this->request->isPost()) {
            $tag = $this->request->param('newTag');

            $find = Db::name("tags")->where("tag", $tag)->where('type', 3)->find();
            if ($find) {
                $data['code'] = 1;
                $data['msg'] = '已在该标签';
            } else {
                $tid =  Db::name("tags")->insertGetId(['tag' => $tag, 'type' => 3]);
                $newTag = Db::name("tags")->where('id', $tid)->find();
                $data['code'] = 0;
                $data['msg'] = '成功';
                $data['data'] = $newTag;
                $data['tid'] = $tid;
            }
            return $data;
        }
    }


    public function trashed()
    {
        $categoryCtr = new CategoryController();

        $categories = $categoryCtr->apiGetCategorys(0);

        $this->assign('categories', $categories['data']);

        return $this->fetch();
    }
    public function getArticleListTrashed(){
        $map = [];
        $catID = $this->request->param('catID/d', 0, 'intval');
        $keyword = $this->request->param('keyword', '');

        if ($catID) {
            $map[] = ['category_id','=',$catID];
        }
        if ($keyword != '') {
            $map[] = ['title','like',$keyword.'%'];
        }

        $count = ArticleModel::onlyTrashed()->where($map)->count();

        $page = $this->request->param('page',1,'intval');
        $limit = $this->request->param('limit',10,'intval');

        $lists = ArticleModel::onlyTrashed()->where($map)->with('category')->order('id desc')->limit(($page-1)*$limit,$limit)->all();

        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $lists;
        $res['count'] = $count;
        return $res;
    }

    /**
     * 添加文章
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->param();


            $post['issuer'] = get_current_admin_id();
            $post['content'] = htmlspecialchars($post['content']);
            $post['issuer_type'] = 2;
            $post['status'] = 1;

            $res['code'] = 1;
            $res['msg'] = '添加成功！';

            $result = RequirementModel::create($post);
            if ($result === false) {
                $res['code'] = 0;
                $res['msg'] = '添加失败！';
            } else {
                $count = get_option('requirement_count');
                if ($count){
                    set_option('requirement_count',['count'=>( $count['count']+1)]);
                }else{
                    set_option('requirement_count',['count'=>1]);
                }
                $res['url'] = url('requirement/edit', [
                    'id' => $result->id
                ]);
            }
            addLog("添加了新需求:",Db::getLastSql());

            return $res;
        } else {

            $tags = Db::name("tags")->where("type", 3)->all();
            $this->assign("tagList", $tags);

            $typeModel = new RequirementTypeModel();

            $categories = $typeModel->getAll();

            $this->assign('categories', $categories);


            return $this->fetch();
        }
    }

    /**
     * 编辑文章
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            $res['code'] = 1;
            $res['msg'] = '保存成功！';

            $data['content'] = htmlspecialchars($data['content']);

            unset($data['newTag']);
            unset($data['imagelabels']);
            unset($data['newtext']);
            unset($data['selectedtext']);
            unset($data['existedtext']);

            $data['status'] = (isset($data['status']) && $data['status'] == 'on') ? 1 : 0;
            $data['update_time'] = date('Y-m-d H:i:s',time());
            $result = RequirementModel::update($data,['id'=>$data['id']]);

            if ($result === false) {
                $res['code'] = 0;
                $res['msg'] = '保存失败！';
            }
            addLog("修改了需求ID:".$data['id'],Db::getLastSql());

            return $res;
        } else {
            $id = $this->request->param('id/d', 0, 'intval');

            $post = RequirementModel::get($id);

            $tags = Db::name("tags")->where("type", 3)->all();
            $this->assign("tagList", $tags);
            $selectedTag = explode(",",$post['tags']);
            $this->assign("selectedTag", $selectedTag);
            $typeModel = new RequirementTypeModel();

            $categories = $typeModel->getAll();

            $this->assign('categories', $categories);

            $this->assign(['categories'=>$categories,'post'=>$post,'data'=>$post]);

            return $this->fetch();
        }
    }
    /**
     * 编辑文章
     */
    public function look()
    {
            $id = $this->request->param('id/d', 0, 'intval');
            $post = RequirementModel::with(["teacher", "member"])->get($id);
            $post['content']= htmlspecialchars_decode($post['content']);
            $typeModel = new RequirementTypeModel();
            $categories = $typeModel->getAll();

            $getList = Db::name('requirement_contact')->where('rid',$id)->order('id','desc')->all();

            foreach ($getList as $key => $value){
                $user = null;
                if ($value['user_type'] == 0){
                    $getList[$key]['user'] = TeacherModel::where('id',$value['uid'])->find();
                }else{
                    $getList[$key]['user'] = MemberModel::where('id',$value['uid'])->find();
                }
            }

            $this->assign('categories', $categories);
            $this->assign('getList', $getList);
            $this->assign(['post'=>$post,'data'=>$post]);
            return $this->fetch();
    }

    /**
     * @return mixed
     * @throws \think\Exception\DbException
     */

    public function getSelectedTagList(){
        $id = input("param.id");
        if ($id){
            $teacher = Db::name("requirement")->get($id);
            $selectedTags = Db::name("tags")->where("id","in",$teacher['tags'])->field("id,tag")->all();
            $allTags = Db::name("tags")->field("id,tag")->all();
            $data['code'] = 1;
            $data['tags'] = $selectedTags;
            $data['allTags'] = $allTags;
        }else{
            $allTags = Db::name("tags")->field("id,tag")->all();
            $data['code'] = 1;
            $data['tags'] = [];
            $data['allTags'] = $allTags;
        }
        return $data;
    }



    /**
     * 加入回收站
     * @return mixed
     */
    public function recycle()
    {
        $param = $this->request->param();

        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');

            ArticleModel::destroy($id);

            $res['code'] = 1;
            $res['msg'] = '回收成功！';
            return $res;
        }

        if (isset($param['ids'])) {
            $ids = $this->request->param('ids/a');
            ArticleModel::destroy($ids);

            $res['code'] = 1;
            $res['msg'] = '回收成功！';
            return $res;
        }
    }

    /**
     * 彻底删除数据
     * @return mixed
     */
    public function delete()
    {
        $param = $this->request->param();

        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');

            Db::name("requirement")->delete($id);

            $res['code'] = 1;
            $res['msg'] = '删除成功！';

            addLog("删除了需求ID:".$id,Db::getLastSql());

            return $res;
        }

        if (isset($param['ids'])) {
            $ids = $this->request->param('ids/a');
            Db::name("requirement")->where('id','in',$ids)->delete();
            $res['code'] = 1;
            $res['msg'] = '删除成功！';
            return $res;
        }
    }

    /**
     * 恢复文章到列表
     * @author Eric
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function restore()
    {
        $param = $this->request->param();

        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');

            $article = ArticleModel::onlyTrashed()->get($id);
            $article->restore();

            $res['code'] = 1;
            $res['msg'] = '恢复成功！';
            return $res;
        }
    }

    /**
     * 显示/开启操作
     *
     * @author Eric ieyangxiaoguo@126.com
     * @date 2017年11月29日
     */
    public function doSwitch()
    {
        return parent::switchOperate(new RequirementModel());
    }

    /**
     * 更新字段
     */
    public function updateField()
    {
        return parent::fieldUpdate(new RequirementModel());
    }

}
